package jdk.thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;


/**
 * 实现一个简单的锁（使用Object的wait()/notify()实现）
 */
public class MyLock implements Lock {

    private boolean hasLocked = false;

    @Override
    public synchronized void lock() {
        while (hasLocked){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if(!hasLocked){
            hasLocked = true;
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        if(hasLocked){
            hasLocked = false;
            notifyAll();
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
